#!/bin/bash

if [ $# -ne 1 ]; then 
	echo "
		$(basename $0) - Verify connections from a master server to a slave DNS server

		Usage:
			
		$(basename $0) DNS-slave
"
	exit 1	
fi

if [ "X$(uname -s)" == "XSunOS" ]; then
    GREP="/usr/xpg4/bin/grep"
    SED="/usr/xpg4/bin/sed"
else
    GREP="/bin/grep"
    SED="/bin/sed"
fi

# . /etc/named/IT_DNS_SERVERS
# PRIMARY=$(echo $DNS_PRIMARY_MASTER)

PRIMARY="phxitdns01.vip.its.ebay.com"
TESTDOMAIN="vip.its.ebay.com"

slave=$(host $1 | awk '/has address/ {print $1}')
slaveip=$(host $1 | awk '/has address/ {print $4}')
hostname=$(echo $slave | awk -F"." '{print $1}')
local=$(host $(hostname) | awk '/has address/ {print $1}')
localip=$(host $(hostname) | awk '/has address/ {print $4}')

echo -e "\nVerify connections from ${local}(${localip}) to slave ${slave}(${slaveip})-"


if [ "X${slave}" == "X" ]; then echo "Error: $1 cannot be resolved." >&2; exit 1; fi

echo -e "verifying 53/TCP with telnet...\t\t\c"

if echo quit | telnet $slave 53 2>/dev/null | $GREP -q "^Escape character is '^]'"; then 
	echo Passed
	echo -e "verifying 53/TCP with dig...\t\t\c"
	if dig @${slave} -t soa $TESTDOMAIN +tcp +short | $GREP -q "^${PRIMARY}"; then
		echo Passed
	else
		echo Failed
	fi
else
	echo Failed
fi

echo -e "verifying 53/UDP with dig...\t\t\c"
if dig @${slave} -t soa $TESTDOMAIN +notcp +short | $GREP -q "^${PRIMARY}"; then
	echo Passed
else
	echo Failed
fi

echo -e "verifying 22/TCP with telnet...\t\t\c"

if echo quit | telnet $slave 22 2>/dev/null | $GREP -q "^Escape character is '^]'"; then 
	echo Passed
	echo -e "verifying 22/TCP with ssh...\t\t\c"
	if ssh -q -o ConnectTimeout=30 -o BatchMode=yes -o StrictHostKeyChecking=no $slave "hostname" 2>/dev/null | $GREP -q "^${hostname}$"; then
		echo Passed
	else
		echo Failed
	fi
	
else
	echo Failed
fi
